package com.ruoyi.fin.controller;

import java.text.SimpleDateFormat;
import java.util.*;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.math.BigDecimal;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.fin.domain.FinTransaction;
import com.ruoyi.fin.service.IFinTransactionService;
import com.ruoyi.fin.mapper.FinTransactionMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

/**
 * 财务利润报表控制器
 * 
 * @author ruoyi
 */
@Controller
@RequestMapping("/fin/profit")
public class FinProfitController extends BaseController
{
    @Autowired
    private IFinTransactionService finTransactionService;
    
    @Autowired
    private FinTransactionMapper finTransactionMapper;

    /**
     * 获取利润数据
     */
    @GetMapping("/data")
    @ResponseBody
    public AjaxResult getProfitData(@RequestParam(required = false, defaultValue = "month") String compareType)
    {
        try {
            // 根据比较类型获取不同的数据
            Map<String, Object> data;
            
            if ("month".equals(compareType)) {
                // 环比数据 - 获取最近6个月的数据
                data = getMonthlyComparisonData();
            } else {
                // 同比数据 - 获取最近12个月的数据，按季度汇总
                data = getYearlyComparisonData();
            }
            
            return AjaxResult.success(data);
        } catch (Exception e) {
            return AjaxResult.error("获取利润数据失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取环比数据（最近6个月）
     */
    private Map<String, Object> getMonthlyComparisonData() {
        Map<String, Object> result = new HashMap<>();
        List<String> categories = new ArrayList<>();
        List<Double> income = new ArrayList<>();
        List<Double> expense = new ArrayList<>();
        List<Double> profit = new ArrayList<>();
        
        // 获取最近6个月的日期范围
        LocalDate now = LocalDate.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM");
        DateTimeFormatter displayFormatter = DateTimeFormatter.ofPattern("yyyy年MM月");
        
        for (int i = 5; i >= 0; i--) {
            LocalDate monthDate = now.minusMonths(i);
            LocalDate startOfMonth = monthDate.withDayOfMonth(1);
            LocalDate endOfMonth = monthDate.with(TemporalAdjusters.lastDayOfMonth());
            
            // 查询当月的交易记录
            String monthStart = startOfMonth.toString();
            String monthEnd = endOfMonth.toString();
            
            // 获取收入和支出
            Map<String, Object> incomeParams = new HashMap<>();
            incomeParams.put("startDate", monthStart);
            incomeParams.put("endDate", monthEnd);
            incomeParams.put("type", "1"); // 收入类型
            
            Map<String, Object> expenseParams = new HashMap<>();
            expenseParams.put("startDate", monthStart);
            expenseParams.put("endDate", monthEnd);
            expenseParams.put("type", "2"); // 支出类型
            
            // 获取收入
            BigDecimal monthIncome = finTransactionMapper.selectTotalAmountByDateRangeAndType(incomeParams);
            if (monthIncome == null) {
                monthIncome = BigDecimal.ZERO;
            }
            
            // 获取支出
            BigDecimal monthExpense = finTransactionMapper.selectTotalAmountByDateRangeAndType(expenseParams);
            if (monthExpense == null) {
                monthExpense = BigDecimal.ZERO;
            }
            
            // 计算利润
            BigDecimal monthProfit = monthIncome.subtract(monthExpense);
            
            // 添加到数据列表
            categories.add(monthDate.format(displayFormatter));
            income.add(monthIncome.doubleValue());
            expense.add(monthExpense.doubleValue());
            profit.add(monthProfit.doubleValue());
        }
        
        result.put("categories", categories);
        result.put("income", income);
        result.put("expense", expense);
        result.put("profit", profit);
        
        return result;
    }
    
    /**
     * 获取同比数据（最近4个季度）
     */
    private Map<String, Object> getYearlyComparisonData() {
        Map<String, Object> result = new HashMap<>();
        List<String> categories = new ArrayList<>();
        List<Double> income = new ArrayList<>();
        List<Double> expense = new ArrayList<>();
        List<Double> profit = new ArrayList<>();
        
        // 获取最近4个季度的日期范围
        LocalDate now = LocalDate.now();
        int currentQuarter = (now.getMonthValue() - 1) / 3 + 1;
        LocalDate quarterStart = now.withMonth((currentQuarter - 1) * 3 + 1).withDayOfMonth(1);
        
        for (int i = 3; i >= 0; i--) {
            LocalDate startDate = quarterStart.minusMonths(i * 3);
            int quarterNum = (startDate.getMonthValue() - 1) / 3 + 1;
            int year = startDate.getYear();
            
            LocalDate endDate = startDate.plusMonths(2).with(TemporalAdjusters.lastDayOfMonth());
            
            // 查询当季度的交易记录
            String qStart = startDate.toString();
            String qEnd = endDate.toString();
            
            // 获取收入和支出
            Map<String, Object> incomeParams = new HashMap<>();
            incomeParams.put("startDate", qStart);
            incomeParams.put("endDate", qEnd);
            incomeParams.put("type", "1"); // 收入类型
            
            Map<String, Object> expenseParams = new HashMap<>();
            expenseParams.put("startDate", qStart);
            expenseParams.put("endDate", qEnd);
            expenseParams.put("type", "2"); // 支出类型
            
            // 获取收入
            BigDecimal quarterIncome = finTransactionMapper.selectTotalAmountByDateRangeAndType(incomeParams);
            if (quarterIncome == null) {
                quarterIncome = BigDecimal.ZERO;
            }
            
            // 获取支出
            BigDecimal quarterExpense = finTransactionMapper.selectTotalAmountByDateRangeAndType(expenseParams);
            if (quarterExpense == null) {
                quarterExpense = BigDecimal.ZERO;
            }
            
            // 计算利润
            BigDecimal quarterProfit = quarterIncome.subtract(quarterExpense);
            
            // 添加到数据列表
            categories.add(year + "年Q" + quarterNum);
            income.add(quarterIncome.doubleValue());
            expense.add(quarterExpense.doubleValue());
            profit.add(quarterProfit.doubleValue());
        }
        
        result.put("categories", categories);
        result.put("income", income);
        result.put("expense", expense);
        result.put("profit", profit);
        
        return result;
    }
} 